﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AzukiMap.DataSource;
using AzukiMap.Map;
using Geotools.Geometries;
using System.Windows.Media.Imaging;
using AzukiMap.Tools.Logger;

namespace AzukiMap.Layer
{
    public class WMSLayer : RasterLayer
    {
        WMSProvider _wmsRasterSource;
        GeometryUtil _geoUtil;

        public WMSLayer(WMSProvider wmsRasterSource, MapCanvas mapCanvas, string name, GTPolygon maxExtent)
            : base(wmsRasterSource, mapCanvas, name,maxExtent)
        {
            init(wmsRasterSource);
        }

        public WMSLayer(WMSProvider wmsRasterSource, MapCanvas mapCanvas, string name)
            : base(wmsRasterSource, mapCanvas, name)
        {
            init(wmsRasterSource);
        }

        void init(WMSProvider wmsRasterSource)
        {
            _wmsRasterSource = wmsRasterSource;
            _geoUtil = new GeometryUtil();
        }

        public override void Draw()
        {
            if (! CheckMaxExtent() || ! CheckScale())
            {
                Logger.Debug("WMSLayer.Draw(): Drawing was skipped.");
                return;
            }
            Image rasterImage = new Image();

            int w = GetImageWidth();
            int h = GetImageHeight();
            _wmsRasterSource.Width = w;
            _wmsRasterSource.Height = h;
            _wmsRasterSource.Bbox = _mapCanvas.CurrentExtent.GetEnvelopeInternal();

            BitmapImage imageSource = new BitmapImage(_wmsRasterSource.ImageUri);
            
            //GTPoint origin = GetImageOrigin();
            rasterImage.SetValue(Canvas.LeftProperty, _mapCanvas.AdjX * -1);
            rasterImage.SetValue(Canvas.TopProperty, _mapCanvas.AdjY * -1);

            rasterImage.Source = imageSource;
            
            _mapCanvas.Children.Add(rasterImage);

        }

        int GetImageWidth()
        {
            return (int)(_mapCanvas.ScreenWidth + _bufferWidth * 2);
        }

        int GetImageHeight()
        {
            return (int)(_mapCanvas.ScreenHeight + _bufferHeight * 2);
        }

    }
}
